package com.repro.baseModule

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.webkit.*
import androidx.annotation.RequiresApi
import com.repro.baseModule.databinding.DemoWebViewBinding
import com.repro.lib_base.bases.activity.BaseActivity
import com.repro.lib_base.bases.activity.ToolBarView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.File

class WebViewActivity : BaseActivity<DemoWebViewBinding>() {
    override fun onToolbarSetting(): ToolBarView? {
        return null
    }

    override fun observeLiveData() {
    }

    @SuppressLint("JavascriptInterface")
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    override fun setViewData(savedInstanceState: Bundle?) {
        val settings = binding.webView.settings
        settings.javaScriptCanOpenWindowsAutomatically = true//设置允许JS弹窗
        settings.domStorageEnabled = true
        //支持缩放
        settings.allowFileAccess = false
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        //支持加载file://本地游戏
        settings.allowFileAccess = true
        settings.allowFileAccessFromFileURLs = true// 设置是否允许通过 file url 加载的 Js代码读取其他的本地文件
        settings.setAllowUniversalAccessFromFileURLs(true)// 设置是否允许通过 file url 加载的 Javascript 可以访问其他的源(包括http、https等源)
        //支持js
        settings.javaScriptEnabled = true
        binding.webView.addJavascriptInterface(JSBridge(),"appJS")
        binding.webView.isHorizontalScrollBarEnabled = false //水平不显示
        binding.webView.isVerticalScrollBarEnabled = false //垂直不显示
        binding.webView.clearCache(true)//清除缓存

        binding.webView.loadUrl("file:///android_asset/7/index.html")

        binding.webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                return false
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
            }
        }
    }

    private inner class JSBridge {

        fun getGameNeedInfo(): String {
            val jsonObject = JSONObject()
            return jsonObject.toString()
        }
    }
}